<template>
<div class="app-container">
   <loading v-show="loading"></loading>
  <el-card class="box-card searchFormStyle" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>权限操作</span>
    </div>
    <div class="text item">
      <el-form ref="SearchRole" :model="SearchRole" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="权限名称"  prop="name">
              <el-input v-model="SearchRole.roleName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button type="primary" 
              icon="el-icon-plus" 
              v-if="permissionHandle('jurisdiction:openDialog')"
              @click="addRole" >新 增</el-button>
              <el-button type="primary" 
              icon="el-icon-search" 
              v-if="permissionHandle('jurisdiction:getList')"
              @click="searchRole" >查 询</el-button>
              <el-button type="primary" 
              icon="el-icon-refresh" 
              v-if="permissionHandle('jurisdiction:getList')"
              @click="resetSearch" >重 置</el-button>
              <el-button type="info" 
              icon="el-icon-delete"
              v-if="permissionHandle('jurisdiction:handleDelete')" 
              @click="BatchDeleting" >删 除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </el-card>
  <el-card class="box-card" style="margin-bottom:1%;">
    <div slot="header" class="clearfix">
      <span>权限列表</span>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%;margin-bottom:1%;"
      @selection-change="handleSelectionChange"
      >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="资源名称"
        width="180">
        <template slot-scope="scope">
            {{ scope.row.name }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="id" >
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column> -->
      <el-table-column label="父级">
        <template slot-scope="scope">
          {{ scope.row.pId }}
        </template>
      </el-table-column>
      <el-table-column label="前台url" min-width="200px">
        <template slot-scope="scope">
          {{ scope.row.frontUrl }}
        </template>
      </el-table-column>
      <el-table-column label="后端的URL" min-width="200px">
        <template slot-scope="scope">
          {{ scope.row.backUrl }}
        </template>
      </el-table-column>
      <el-table-column label="资源类型">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      <el-table-column
        width="180"
        label="创建日期">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="260px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-edit-outline"
            v-if="permissionHandle('jurisdiction:handleEdit')" 
            @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            v-if="permissionHandle('jurisdiction:handleDelete')" 
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagerCount" :page-sizes="[10,20,30, 50]" :page-size="10" layout="sizes, prev, pager, next" :total="200">
    </el-pagination> -->
    <el-pagination
      background
      layout="prev, pager, next"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-count="totalPage">
    </el-pagination>
  </el-card>
  <!---------------------------------------------------------------------新增角色-->
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="addMenu" :rules="rules" ref="addMenu" label-width="100px">
      <el-row>
        <!-- <el-col :span="12">
            <el-form-item label="id" >
              <el-input v-model="addMenu.id" ></el-input>
            </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="父级菜单" >
              <el-popover
                placement="bottom"
                width="300"
                trigger="click">
                 <el-tree
                  :data="pId"
                  :props="defaultProps"
                  accordion
                  @node-click="handleNodeClick"
                  >
                </el-tree>
                <el-input v-model="addMenu.pName"  slot="reference" readonly></el-input>
              </el-popover>
              <el-input type="hidden" v-model="addMenu.pId" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="addMenu.name" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="前台URL" prop="frontUrl">
            <el-input v-model="addMenu.frontUrl" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="后台URL" prop="backUrl">
            <el-input v-model="addMenu.backUrl" auto-complete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="类型" >
            <el-select v-model="addMenu.type" placeholder="请选择角色状态">
              <el-option
                v-for="item in menuType"
                :key="item.id"
                :label="item.paramName"
                :value="item.paramNumber">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="roleSubmitSuccess('addMenu')">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>
<script>
import Loading from '@/components/loading/loading'
import { transform } from '@/utils/trans'
import { isvalidSpecial } from '@/utils/validate'
// import treeTable from '@/components/TreeTable'

// 特殊字符
var validSpecial = (rule, value, callback) => {
  if (!isvalidSpecial(value)) {
    callback(new Error('数据不能包含特殊字符'))
  } else {
    callback()
  }
}

import { MenuList, add, addAllMenu, delMenu } from '@/api/resource/jurisdiction'
export default {
  components: {
    Loading
  },
  data() {
    this.permissionHandle = this.$permissionHandle
    return {
      pId: [],
      menuType: [],
      SearchRole: {
        roleName: ''
      },
      loading: false,
      authloading: false,
      options: [{
        value: 1,
        label: '可用'
      }, {
        value: 0,
        label: '禁用'
      }],
      tableData: [],
      // 新增角色数据
      addMenu: {
        pId: '',
        pName: ''
      },
      dialogFormVisible: false, // 新增弹出框状态
      // 列表所选数据集合
      multipleSelection: [],
      totalPage: 1,
      dialogAuthVisible: false, // 授权弹出框状态
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      roleId: '',
      allAuth: [],
      flag: 1,
      typeRole: [],
      dataList: [],
      roleKey: '',
      title: '',
      rules: {
        name: [
          { message: '数据不能包含特殊字符', validator: validSpecial }
        ],
        frontUrl: [
          { message: '数据不能包含特殊字符', validator: validSpecial }
        ],
        backUrl: [
          { message: '数据不能包含特殊字符', validator: validSpecial }
        ]
      },
      currentPage: 1,
      checkdefault: []// 默认授权
    }
  },
  created() {
    if (this.permissionHandle('jurisdiction:getList')) {
      this._roleList()
    } else {
      this.$router.push({
        path: 'dashboard',
        name: '首页'
      })
    }
  },
  methods: {
    resetSearch() {
      this.SearchRole = {
        roleName: ''
      }
      this._roleList()
    },
    handleNodeClick(data) {
      this.addMenu.pName = data.name
      this.addMenu.pId = data.id
    },
    // 获取角色数据
    _roleList() {
      this.handleCurrentChange(1)
    },
    // 点击新增角色
    addRole() {
      this.loading = true
      this.title = '新增权限'
      this.roleKey = []
      this.dialogFormVisible = true
      this.addMenu = {
        id: '',
        pId: '',
        name: '',
        frontUrl: '',
        backUrl: '',
        type: ''
      }
      add().then(res => {
        this.loading = false
        this.pId = transform(res.data.resourcesList, 'id', 'pId', 'children')
        this.menuType = res.data.resourceType
        this.addMenu.pName = this.menuType.name
      })
    },
    // 新增成功
    roleSubmitSuccess(addMenu) {
      this.loading = true
      this.dialogFormVisible = false
      addAllMenu({
        id: this.addMenu.id,
        pId: this.addMenu.pId,
        name: this.addMenu.name,
        frontUrl: this.addMenu.frontUrl,
        backUrl: this.addMenu.backUrl,
        type: this.addMenu.type
      }).then(res => {
        if (res.code === 200) {
          this.openwarning('提交成功', 'success')
          this.handleCurrentChange(1)
          this.$refs.addForm.resetFields()
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 角色查询
    searchRole() {
      this.handleCurrentChange(1)
      // this.tableData = 1
    },
    // 编辑角色
    handleEdit(index, row) {
      this.title = '修改权限'
      this.dialogFormVisible = true
      // this.roleKey = row.roleKey
      // debugger
      add({ id: row.id }).then(res => {
        this.pId = transform(res.data.resourcesList, 'id', 'pId', 'children')
        this.menuType = res.data.resourceType
        this.addMenu = res.data.entity
        this.addMenu.pName = res.data.entity.name
        res.data.resourceType.forEach(val => {
          // debugger
          if (val.paramValue === res.data.entity.type) {
            this.addMenu.type = val.paramNumber
            this.addMenu.typeNumber = val.paramNumber
          }
        })
        res.data.resourcesList.forEach(val => {
          // debugger
          if (val.id === res.data.entity.pId) {
            // debugger
            this.addMenu.pName = val.name
            this.addMenu.pId = val.id
          }
        })
      })
    },
    // 批量删除
    BatchDeleting() {
      if (this.multipleSelection.length !== 0) {
        const result = []
        this.multipleSelection.forEach(val => {
          result.push(val.id)
        })
        delMenu({
          // ids: [result.join(',')]
          'ids': JSON.stringify(result)
        }).then(res => {
          if (res.code === 200) {
            this.handleCurrentChange(1)
            this.openwarning('删除成功', 'success')
          }
        }).catch(error => {
          console.log(error)
        })
      } else {
        this.openwarning('请选择要删除数据', 'warning')
      }
    },
    handleDelete(index, row) { // 行内删除
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this._delRole(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    _delRole(row) {
      delMenu({
        ids: JSON.stringify([row.id])
      }).then(res => {
        if (res.code === 200) {
          this.handleCurrentChange(1)
        }
      }).catch(error => {
        console.log(error)
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // handleSizeChange(val) {
    //   console.log(val)
    // },
    handleCurrentChange(val) {
      console.log(val)
      this.loading = true
      MenuList({
        name: this.SearchRole.roleName,
        pageSize: 10,
        pageNum: val
      }).then(res => {
        if (res.code === 200) {
          this.loading = false
          console.log(res.data.items)
          console.log(res.data)
          this.currentPage = val
          this.tableData = res.data.items
          this.totalPage = res.data.pageTotalCount
        }
      }).catch(error => {
        this.loading = false
        console.log(error)
      })
    },
    openwarning(mes, type) {
      this.$message({
        showClose: true,
        message: mes,
        duration: 2000,
        type: type
      })
    }
  }
}
</script>
<style >
.dialog-footer{
  text-align: right;
  margin-top: 50px;
  /* position: absolute;
  margin-top: 0;
  right: 0; */
}
.el-table thead{
  vertical-align: middle !important;
}

/* .el-tree-node .el-tree-node__children {
    display: flex!important;
    flex-wrap: wrap!important;
} */

</style>
